package com.raymond.queue;

import com.raymond.queue.common.codec.AgreementDecoder;
import com.raymond.queue.common.codec.BaseCodecStrategy;
import com.raymond.queue.common.netty.MsgDecoder;
import com.raymond.queue.common.netty.MsgEncoder;
import com.raymond.queue.handler.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @author :  raymond
 * @version :  V1.0
 * @date :  2021-07-13 11:33
 */
public class ServerRun {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        BaseCodecStrategy.init("com.raymond.queue.codec");
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new IdleStateHandler(3 * 60, 0, 0));
                            pipeline.addLast(new ServerIdleStateTrigger());
                            pipeline.addLast(new LengthFieldBasedFrameDecoder(10 * 1024 * 1024 , 0, 4, -4, 0, true));
                            pipeline.addLast(new AgreementDecoder());
                            pipeline.addLast(new MsgDecoder());
                            pipeline.addLast(new MsgEncoder());
                            pipeline.addLast(new ProductionMsgRequestHandler());
                            pipeline.addLast(new ConsumptionMsgRequestHandler());
                            pipeline.addLast(new CreateTopicRequestHandler());
                            pipeline.addLast(new CreateConsumptionRequestHandler());
                            pipeline.addLast(new HeartbeatHandler());
                        }
                    });
            System.out.println("netty server start。。9000");
            ChannelFuture channelFuture = serverBootstrap.bind(9000).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
